package com.itheima.activities.task;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.itheima.activities.service.RedPacketService;
import com.itheima.entity.pojo.RedPacketList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author :wujunjie
 * createTime :2022-12-19 21:32
 * description :
 */
@Component
@Slf4j
public class PutRedPacketListOnline {
    @Autowired
    private RedPacketService redPacketService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Scheduled(fixedRate =5*1000)
    @Transactional
    public void task(){
        List<RedPacketList> redPacketLists = redPacketService.selectRedPacketListsByStatusAndTime();
        if (ObjectUtil.isEmpty(redPacketLists)){
            log.info("库中符合条件的红包已全部都上线");
            return;
        }
        Map<String, List<RedPacketList>> redPacketListMap = redPacketLists.stream().collect(Collectors.groupingBy(RedPacketList::getRedPacketId));
        Set<String> redPacketIds = redPacketListMap.keySet();
        for (String redPacketId : redPacketIds) {
            for (RedPacketList redPacketList : redPacketListMap.get(redPacketId)) {
                redisTemplate.opsForList().leftPush("redPacketId:"+redPacketId, JSON.toJSONString(redPacketList));
            }
        }
        Boolean updateRedPacketListStatus=redPacketService.updateRedPacketListStatus(redPacketLists);
        if (updateRedPacketListStatus){
            log.info("成功上线一波红包");
        }
    }


}
